﻿using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEngine;

namespace XUBugly
{
    namespace Editor
    {
        public class BuglyPostProcessBuild
        {
            [PostProcessBuild(1)]
            public static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject)
            {
                if (target != BuildTarget.iOS)
                {
                    Debug.LogWarning("Target is not iOS. BuglyPostProcessBuild will not run");
                    return;
                }

                string projmodsFromPath = "Bugly.projmods";
                {
                    List<string> allFiles = new List<string>();
                    string folder1 = Application.dataPath.Replace("Assets", "Packages");
                    string folder2 = Application.dataPath.Replace("Assets", "Library/PackageCache");
                    allFiles.AddRange(Directory.GetFiles(folder1, projmodsFromPath, SearchOption.AllDirectories));
                    allFiles.AddRange(Directory.GetFiles(folder2, projmodsFromPath, SearchOption.AllDirectories));
                    foreach (string file in allFiles)
                    {
                        projmodsFromPath = Path.GetDirectoryName(file) + "/Bugly.framework";
                        if (Directory.Exists(projmodsFromPath))
                        {
                            projmodsFromPath = Path.GetDirectoryName(file);
                            break;
                        }
                    }
                }

                string projmodsToPath = pathToBuiltProject + "/Bugly";
                XUBuglyUtil.CopyFolder(projmodsFromPath, projmodsToPath);
            }
        }
    }
}
